<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="人员名称" prop="employeePeopleName">
        <el-input
          v-model="queryParams.employeePeopleName"
          placeholder="请输入从业人员名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-select v-model="queryParams.isRecommend" placeholder="请选择是否推荐" clearable size="small">
          <el-option
            v-for="dict in isRecommendOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="在线状态" prop="isOnline">
        <el-select v-model="queryParams.isOnline" placeholder="请选择在线状态" clearable size="small">
          <el-option
            v-for="dict in isOnlineOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wechat:employeepeople:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wechat:employeepeople:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wechat:employeepeople:remove']"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="employeepeopleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column label="人员名称" align="center" prop="employeePeopleName" />
      <el-table-column label="人员手机号" align="center" prop="employeePeoplePhone" />
      <el-table-column label="所在公司" align="center" prop="employeePeopleCompany" />
      <!-- <el-table-column
        label="是否推荐"
        align="center"
        prop="isRecommend"
        :formatter="isRecommendFormat"
      />-->

      <el-table-column label="是否推荐" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRecommend"
            active-value="0"
            inactive-value="1"
            @change="handleRecommendChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" align="center" prop="isOnline" :formatter="isOnlineFormat" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="从业人员状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wechat:employeepeople:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wechat:employeepeople:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改从业人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <!-- <el-form-item label="人员类型编号" prop="employeeTypeId">
          <el-input v-model="form.employeeTypeId" placeholder="请输入人员类型编号" />
          </el-form-item>-->
          <el-col :span="12">
            <el-form-item label="人员头像" prop="employeePeopleAvatarUrl">
              <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :show-file-list="false"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
              >
                <img
                  v-if="form.employeePeopleAvatarUrl"
                  :src="form.employeePeopleAvatarUrl"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员名称" prop="employeePeopleName">
              <el-input v-model="form.employeePeopleName" placeholder="请输入人员名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="employeePeoplePhone">
              <el-input v-model="form.employeePeoplePhone" placeholder="请输入人员手机号" />
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员职称" prop="employeePeoplePost">
              <el-input v-model="form.employeePeoplePost" placeholder="请输入人员职称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在公司" prop="employeePeopleCompany">
              <el-input v-model="form.employeePeopleCompany" placeholder="请输入人员所在公司" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number
                style="width:100%"
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="在线状态">
              <el-select v-model="form.isOnline" placeholder="请选择在线状态">
                <el-option
                  v-for="dict in isOnlineOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否推荐">
              <el-select v-model="form.isRecommend" placeholder="请选择是否推荐">
                <el-option
                  v-for="dict in isRecommendOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员标签" prop="employeePeopleTags">
              <!-- <el-input v-model="form.employeePeopleTags" placeholder="请输入人员标签" /> -->
              <treeselect
                :multiple="true"
                :options="tagOptions"
                :disable-branch-nodes="true"
                placeholder="选择人员标签"
                v-model="selectValue"
                :default-expand-level="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="人员介绍" prop="employeePeopleIntro">
              <el-input v-model="form.employeePeopleIntro" type="textarea" placeholder="请输入人员介绍" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.el-form-item--medium .el-form-item__content {
  line-height: 20px;
}
.el-upload-dragger {
  width: 180px;
  height: 120px;
}
.el-upload-dragger .el-icon-upload {
  margin: 14px 0 16px;
}
.el-upload-dragger .el-upload__text {
  font-size: 12px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
<script>
import {
  listEmployeepeople,
  getEmployeepeople,
  delEmployeepeople,
  addEmployeepeople,
  updateEmployeepeople,
  exportEmployeepeople,
  changeRecommendStatus
} from "@/api/wechat/employeepeople";

import { treeselectByType } from "@/api/wechat/employeetype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
export default {
  components: { Treeselect },
  data() {
    return {
      tagOptions: [],
      selectValue: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 从业人员表格数据
      employeepeopleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否推荐字典
      isRecommendOptions: [],
      // 在线状态字典
      isOnlineOptions: [],
      // 默认密码
      initPassword: undefined,
      // 从业人员状态字典
      statusOptions: [],
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeePeopleName: undefined,
        isRecommend: undefined,
        isOnline: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        employeeTypeId: [
          {
            required: true,
            message: "从业人员类型编号不能为空",
            trigger: "blur"
          }
        ],
        employeePeopleName: [
          { required: true, message: "从业人员名称不能为空", trigger: "blur" }
        ],
        employeePeoplePhone: [
          { required: true, message: "从业人员手机号不能为空", trigger: "blur" }
        ],
        employeePeoplePost: [
          { required: true, message: "请选择从业人员职称", trigger: "blur" }
        ],
        employeePeopleCompany: [
          { required: true, message: "请选择从业人员所在公司", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入从业人员密码", trigger: "blur" }
        ],
        employeePeopleAvatarUrl: [
          { required: true, message: "请选择从业人员头像", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.employeeTypeId =
      this.$route.params && this.$route.params.employeeTypeId;
    console.log(this.employeeTypeId);
    this.getTreeselect();
    this.getList();
    this.getDicts("sys_employee_is_recommend").then(response => {
      this.isRecommendOptions = response.data;
    });
    this.getDicts("sys_employee_online_status").then(response => {
      this.isOnlineOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      this.treeParams = {};
      this.treeParams.employeeTypeId = this.employeeTypeId;
      treeselectByType(this.treeParams).then(response => {
        this.tagOptions = response.data;
      });
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleRecommendChange(row) {
      console.log(row.isRecommend);
      let text = row.isRecommend == 0 ? "推荐" : "停止推荐";
      this.$confirm(
        '确认要"' + text + '""' + row.employeePeopleName + '"用户吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return changeRecommendStatus(
            row.employeePeopleId,
            row.isRecommend == 1 ? 1 : 0
          );
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function() {
          row.isRecommend = row.isRecommend == 0 ? 1 : 0;
        });
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
      }
    },
    handleUploadSuccess(res, file) {
      this.form.employeePeopleAvatarUrl = res.url;
    },
    /** 查询从业人员列表 */
    getList() {
      this.loading = true;
      this.queryParams.employeeTypeId = this.employeeTypeId;
      listEmployeepeople(this.queryParams).then(response => {
        this.employeepeopleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否推荐字典翻译
    isRecommendFormat(row, column) {
      return this.selectDictLabel(this.isRecommendOptions, row.isRecommend);
    },
    // 在线状态字典翻译
    isOnlineFormat(row, column) {
      return this.selectDictLabel(this.isOnlineOptions, row.isOnline);
    },
    // 从业人员状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        employeePeopleId: undefined,
        employeeTypeId: this.employeeTypeId,
        employeePeopleName: undefined,
        employeePeoplePhone: undefined,
        password: undefined,
        employeePeopleAvatarUrl: undefined,
        employeePeoplePost: undefined,
        employeePeopleCompany: undefined,
        employeePeopleIntro: undefined,
        employeePeopleTags: undefined,
        isRecommend: "0",
        isOnline: "0",
        orderNum: 1,
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.employeePeopleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.password = this.initPassword;
      this.open = true;
      this.title = "添加从业人员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const employeePeopleId = row.employeePeopleId || this.ids;
      getEmployeepeople(employeePeopleId).then(response => {
        this.form = response.data;
        if (this.form.employeePeopleTags) {
          this.selectValue = this.form.employeePeopleTags.split(",").map(item => {
            return Number(item);
          });
        } else this.selectValue = [];
        console.log(this.form.employeePeopleTags);
        this.open = true;
        this.title = "修改从业人员";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.form.employeePeopleTags = this.selectValue.join(",");
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.employeePeopleId != undefined) {
            updateEmployeepeople(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addEmployeepeople(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const employeePeopleIds = row.employeePeopleId || this.ids;
      this.$confirm(
        '是否确认删除从业人员编号为"' + employeePeopleIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delEmployeepeople(employeePeopleIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有从业人员数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportEmployeepeople(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    }
  }
};
</script>